package gui.catalogues.persons;

import gui.catalogues.persons.interfaces.PersonTableListener;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import model.Person;

public class PersonTablePanel extends JPanel {
	
	/*
	 * Variable declaration
	 * */
	private JTable t;
	private JPopupMenu popUpMenu;
	private JMenuItem jmiDeleteRow;
	private int rowNum;
	private PersonTableListener personTableListener;
	
	private PersonTableModel personTableModel;
	Dimension dim = getPreferredSize();
	
	public PersonTablePanel() {
		/*
		 * Variable initialization
		 * */
		personTableModel = new PersonTableModel();	
		
		/*
		 * initializing and assigning popUp variables 
		 * */
		popUpMenu = new JPopupMenu();
		jmiDeleteRow = new JMenuItem("Borrar renglón");
		popUpMenu.add(jmiDeleteRow);
		
		t = new JTable(personTableModel);
		
		dim.height = 100;
		dim.width = 250;
		setPreferredSize(dim);
		setMinimumSize(dim);
		setLayout(new BorderLayout());
		
		add(new JScrollPane(t), BorderLayout.CENTER);
		
		/*
		 * manage actionListeners
		 * */
		manageActionListeners();
	}
	
	public void manageActionListeners() {
		/*
		 * ActionListener to manage the right mouse click over the table
		 * */
		t.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				// if the mouse button is the right one...
				if(e.getButton() == MouseEvent.BUTTON3) {
					// get the row number over which the right click was pressed
					rowNum = t.rowAtPoint(e.getPoint());
					// to set the row, I get its selectionModel and set in It the
					// selection interval (1 to N rows)
					t.getSelectionModel().setSelectionInterval(rowNum, rowNum);
					// parent source table, and XY coordinates
					popUpMenu.show(t, e.getX(), e.getY());
				}
			}
		});
		
		jmiDeleteRow.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// get selected row
				rowNum = t.getSelectedRow();
				
				/*
				 * Will pass a rowDeleted method for the Main class -MainFrame- to implement its own
				 * kind of rowDeleted method.
				 * */
				if(personTableListener != null) {
					personTableListener.rowDeleted(rowNum);
					personTableModel.fireTableRowsDeleted(rowNum, rowNum);
				}
				
				
			}
		});
	}
	
	public void setTableData(List<Person> tableData) {
		personTableModel.setItemList(tableData);
	}
	
	public void refresh() {
		personTableModel.fireTableDataChanged();
	}
	
	public void setPersonTableListener(PersonTableListener personTableListener) {
		this.personTableListener = personTableListener;
	}
}
